package com.changgou.web.gateway.filter;

import com.changgou.web.gateway.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import sun.security.krb5.internal.AuthorizationData;

import java.net.URI;

@Component
public class AuthFilter implements GlobalFilter, Ordered {

    private static final String LOGIN_URL = "http://localhost:8001/api/oauth/toLogin";

    private static final String Authorization = "Authorization";


    @Autowired
    private AuthService authService;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //1.获取当前请求
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //1.1判断请求路径是否为登录路径,如果为登录路径,则放行
        URI uri = request.getURI();
        String path = uri.getPath();
        if ("/api/oauth/login".equals(path) || !URLFilter.hasAuthorize(path)) {
            return chain.filter(exchange);
        }
        //2.判断cookie上是否存在jti
        String jti = authService.getJtiFromCookie(request);
        if (jti == null) {
//            response.setStatusCode(HttpStatus.UNAUTHORIZED);
//            return response.setComplete();

            return toLoginPage(LOGIN_URL + "?FROM=" + request.getURI().getPath(), exchange);
        }

        //3.判断redis中是否存在jwt
        String Jwt = authService.getJwtFromRedis(jti);
        if (Jwt == null) {
//            response.setStatusCode(HttpStatus.UNAUTHORIZED);
//            return response.setComplete();

            return toLoginPage(LOGIN_URL+ "?FROM=" + request.getURI().getPath(), exchange);
        }

        //校验通过,对请求头进行增强,然后放行
        request.mutate().header(Authorization, "Bearer " + Jwt);
        return chain.filter(exchange);
    }

    private Mono<Void> toLoginPage(String loginUrl, ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.SEE_OTHER);
        response.getHeaders().set("Location", loginUrl);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
